package com.lcy.web.controller

import com.lcy.web.base.EmptyStringFilter
import com.lcy.web.bean.User
import org.apache.shiro.SecurityUtils
import org.apache.shiro.authc.UsernamePasswordToken
import org.apache.shiro.authz.annotation.RequiresPermissions
import org.apache.shiro.authz.annotation.RequiresUser
import org.springframework.stereotype.Controller
import org.springframework.validation.annotation.Validated
import java.util.*
import javax.validation.Valid
import javax.validation.constraints.NotNull
import javax.validation.constraints.Size
import javax.validation.executable.ValidateOnExecution
import javax.ws.rs.*
import javax.ws.rs.core.MediaType

/**
 * Created by loucunyin on 6/24/17.
 */
@Controller
@Path("users")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@EmptyStringFilter
@Validated
open class UserController{
    @GET
    @Path("list")
    fun listUsers():Date{
        return Date()
    }

    @GET
    @Path("int")
    fun getInt(@NotNull(message = "number 不能为空") @QueryParam("number") number:Int?,@NotNull(message = "string 不能为空") @QueryParam("string") string:String?):String?{
        throw RuntimeException("test exception handler")
        return "number:$number, string:$string"
    }

    @GET
    @Path("date")
    fun getDate(@QueryParam("date") date: Date?):Date?{
        val subject = SecurityUtils.getSubject()
        subject.checkPermission("menu:admin:1,2")
        return date
    }

    @POST
    @Path("json")
    fun getJson(map:Map<String,Any>?):Map<String,Any>?{
        println(map)
        return map
    }

    @POST
    @Path("add")
    @Valid
    fun addUser( @Valid user:User):User{
        println(user.name)
        return user
    }
    @GET
    @Path("object")
    fun testUser(@QueryParam("test") test:String = ""):Any{
        val subject = SecurityUtils.getSubject()

        subject.checkPermission("menu:admin:$test")
        return subject
    }

    @GET
    @Path("login")
    fun login(@QueryParam("name") name:String,@QueryParam("password")password:String):String{
        val token = UsernamePasswordToken(name,password)
        SecurityUtils.getSubject().login(token)
        return "login success"
    }

    @GET
    @Path("logout")
    fun logout():String{
        val user =SecurityUtils.getSubject().principal.toString()
        SecurityUtils.getSubject().logout()
        return user
    }

}